package com.caltco.cargo.ops.common.utils;

import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.caltco.cargo.ops.common.vo.MessageParams;
import com.caltco.cargo.ops.common.vo.MsgTemplate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * description: WechatUtil 微信工具包
 * date: 2023/3/20 16:48
 * author: yehao
 * version: 1.0
 */
@Component
public class WechatUtil {

    @Value("${wx.appid}")
    private String appid;

    @Value("${wx.secret}")
    private String secret;

    public String getAccessToken(){
        String body = HttpRequest.get("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + secret).execute().body();
        JSONObject jsonObject = JSONUtil.parseObj(body);
        return (String) jsonObject.get("access_token");
    }

    public JSONObject sendMessage(String userId, MsgTemplate params, String templateId, String url){
        String accessToken = getAccessToken();
        MessageParams messageParams = new MessageParams();
        messageParams.setPage(url);
        messageParams.setTouser(userId);
        messageParams.setTemplate_id(templateId);
        messageParams.setData(params);
        JSONObject jsonObject = JSONUtil.parseObj(messageParams);
        String body = HttpRequest.post("https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + accessToken)
                .header("Content-Type", "application/json")
                .body(String.valueOf(jsonObject))
                .execute()
                .body();
        JSONObject res = JSONUtil.parseObj(body);
        return res;
    }



}
